import store from "@/store/index";
const baseURL = "https://pcapi-xiaotuxian-front-devtest.itheima.net";
// 请求拦截器
const request = {
    invoke(args) {
        uni.showLoading({ title: "加载中" });
        if (!args.url.startsWith("http")) {
            args.url = baseURL + args.url;
        }
        args.header = {
            ...args.header, // 保留原本的 header
            "source-client": "miniapp", // 添加小程序端调用标识
        };

        if (store.state.user.userInfo && store.state.user.userInfo.token) {
            // console.log("有token");
            args.header.Authorization = store.state.user.userInfo.token;
        } else {
            console.log("无token");
        }
    },
    complete(res) {
        uni.hideLoading();
    },
};
uni.addInterceptor("request", request);
uni.addInterceptor("uploadFile", request);
// 响应拦截器哦
export default (options) => {
    return new Promise((resolve, reject) => {
        uni.request({
            ...options,
            success(res) {
                if (res.statusCode >= 200 && res.statusCode < 300) {
                    resolve(res.data);
                } else {
                    if (res.statusCode === 401) {
                        setTimeout(() => {
                            uni.navigateBack({ url: '/page/login/index' })
                        }, 1500);

                    }
                    reject(res);
                }
            },
            fail(err) {
                reject(res);
            },
        });
    });
};